// pages/goos_detail/index.ts
import {
  request
} from '../../request/index'
import {
  showModal,
  showToast
} from "../../utils/asyncWx.js";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    detalData: {},
    interval: 2000,
    duration: 500,
    autoplay: true,
    indicatorDots: true,
    info: 0,
    collected: false
  },
  QueryParams: {
    goods_id: 0
  },
  dataList: {},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(option) {
    this.getDetalMes(option.goods_id)
    let cart = wx.getStorageSync('cart') || []
    this.setData({
      info: cart.length
    })
  },
  // 获取商品数据
  async getDetalMes(goods_id) {
    this.QueryParams.goods_id = goods_id
    const dataList = await request({
      url: "goods/detail",
      data: this.QueryParams
    })
    this.dataList = dataList
    this.setData({
      detalData: {
        pics: dataList.pics,
        goods_price: dataList.goods_price,
        goods_name: dataList.goods_name,
        // iphone不识别webp的图片
        goods_introduce: dataList.goods_introduce.replaceAll('.webp', '.jpg')
      },
    })
    let collectGood = wx.getStorageSync('collects') || []
    let goods = collectGood.find(s => s.goods_id == this.dataList.goods_id)
    if (goods) {
      this.setData({
        collected: true
      })
    }
  },
  async collectGoods() {
    let collectGood = wx.getStorageSync('collects') || []
    let index = collectGood.findIndex(s => s.goods_id == this.dataList.goods_id)
    if (index == -1) {
      collectGood.push(this.dataList)
      this.setData({
        collected: true
      })
      await showToast({
        title: '收藏成功'
      })
    } else {
      collectGood.splice(index, 1)
      this.setData({
        collected: false
      })
      await showToast({
        title: '取消成功'
      })
    }
    wx.setStorageSync('collects', collectGood)
  },
  // 图片预览
  image(e) {
    let path = e.target.dataset.id;
    let onself = this;
    let list = onself.data.detalData.pics.map(s => s.pics_mid);
    console.log(list[path])
    wx.previewImage({
      current: list[path], //获取当前路径
      urls: list, //获取查看图片列表
    })
  },
  // 购物车跳转
  onClickCart() {
    wx.switchTab({
      url: '/pages/cart/index',
    })
  },
  // 加入购物车
  addCart() {
    let cart = wx.getStorageSync('cart') || []
    let index = cart.findIndex(s => {
      return s.goods_id === this.dataList.goods_id
    })
    console.log(index);
    if (index == -1) {
      this.dataList.num = 1
      // 选中显示
      this.dataList.checked = true
      cart.push(this.dataList)
    } else {
      cart[index].num++
    }
    wx.setStorageSync('cart', cart)
    this.setData({
      info: cart.length
    })
    wx.showToast({
      title: '加入成功',
      type: 'success',
      mask: true,
    })
  },

})